require "System::Windows::Threading"
require "System::Net"
require "System::Text"
require "System::Collections"
require "System::Collections::Specialized"
require "System::Windows::Media::Imaging"


URLS = {
        :auth => "http://twitter.com/account/verify_credentials.json",
        :friends => "http://twitter.com/statuses/friends_timeline.json",
        :update => "http://twitter.com/statuses/update.json",
        :search => "http://search.twitter.com/search.json"
}

class Twitter
  attr_accessor :presenters
  def initialize
    @hash = ""
    @presenters = []
  end

  def credentials(username, password)
    utf8 = UTF8Encoding();
    @hash = Convert.ToBase64String(utf8.GetBytes("#{username}:#{password}"))
  end

  def friends_timeline
    fetch(URLS[:friends])
  end

  def update(msg)
    url = "#{URLS[:update]}?status=#{msg}"
    fetch(url, "POST")
  end

  def search(query_terms, query_string=nil)
    url = URLS[:search]
    if(query_string)
      url += query_string
    else
      url += "?q=" + query_terms
    end
    fetch(url)
  end

  def update_status_list(sender, args)
    if(args.Error.nil?)
      resp = JsonValue.Parse(args.Result)
      @presenters.each do |presenter|
        presenter.add_to_status_list(resp)
      end
    else
      log(args.Error)
    end
  end

  def fetch(uri, method="GET")
    client = WebClient.new()
    #proxy = "http://localhost/gestalt/TwitterProxy.ashx?u=#{HttpUtility.UrlEncode(uri)}&m=#{HttpUtility.UrlEncode(method)}"
    #if(self.hash)
    #  proxy += "&ph=#{HttpUtility.UrlEncode(@hash)}"
    #end
    #log("calling #{proxy}")
    client.DownloadStringAsync(Uri.new(uri))
    client.DownloadStringCompleted do |s,e|update_status_list(s,e) end  #how do we do delegate assignment in IR?
  end
end


tweets = []
current_tweet = -1
qs = nil

class BadgePresenter
  def add_to_status_list(json)
    qs = json.refresh_url
    json.results.each do |status|
      tweets << {:name=>status.from_user,
                 :image_url=>status.profile_image_url.Replace("\\",""),
                 :text => status.text,
                 :created_at=>DateTime.Parse(status.created_at).ToShortDateString(),
                 :source=>status.source}
    end
  end
end

def ping_twitter(sender, args)
  twitter.search("fallenrogue", qs)
  log("called %s" % DateTime.Now.ToString())
end

def go_to_next_tweet(sender, args)
  if(current_tweet < tweets.length-1):
    current_tweet += 1
    update_ui(tweets[current_tweet])
  end
end

def go_to_previous_tweet(sender, args)
  if(current_tweet >= 1)
    current_tweet -= 1
    update_ui(tweets[current_tweet])
  end
end

def update_ui(data_hash)
  me.status.Text = data_hash[:text]
  me.details.Text = "from #{data_hash[:name]} on #{data_hash[:created_at]} from #{data_hash[:source]}"
  me.avatar.Source = BitmapImage(Uri.new(data_hash[:image_url].to_s))
  me.username.Text = data_hash[:name]
end

def log(msg)
  document.msg.innerHTML = "<p>"+str(msg)+"</p>"
end

twitter = Twitter.new()
twitter.presenters << BadgePresenter.new()
twitter.search(nil, "?tag=gestalt")

ping_timer = DispatcherTimer()
ping_timer.Interval = TimeSpan(0, 0, 0, 30, 0)
ping_timer.Tick { |s, a| ping_twitter(s, a) }
ping_timer.Start()

me.next.Click { |s, a| go_to_next_tweet(s, a) }
me.previous.Click { |s, a| go_to_previous_tweet(s, a) }
